<?php

namespace app\common\controller;

use app\admin\model\Paper;
use app\admin\model\Room;
use app\admin\model\UserNotice;
use app\base\model\User;
use think\Cache;
use think\Request;
use think\Session;

class PortalBase extends Base {
  protected $uid = 0;
  protected $modelUser, $modelPaper, $modelRoom;

  public function __construct(Request $request = NULL) {
    parent::__construct($request);

    $this->modelUser = new User();
    $this->modelPaper = new Paper();
    $this->modelRoom = new Room();

    if (request()->isMobile() && !request()->isAjax()) {
      $this->redirect('/mobile/');
    }
    self::checkLogin();
    self::checkExam();
    $unReads = self::getUnReads();
    if ($unReads) {
      $this->assign('unReads', $unReads);
    }

  }

  public function _initialize() {
    parent::_initialize(); // TODO: Change the autogenerated stub
  }

  public function getUnReads() {
    $module = strtolower(request()->module());
    $controller = strtolower(request()->controller());
    $action = strtolower(request()->action());
    $rule = [
      'portal' => ['room' => '*'],
    ];
    $accept = FALSE;
    if (isset($rule[ $module ][ $controller ])) {
      if ($rule[ $module ][ $controller ] === '*' || in_array($action, $rule[ $module ][ $controller ])) {
        $accept = TRUE;
      }
    }
    if (!$accept) {
      $modelUserNotice = new UserNotice();

      return $modelUserNotice->unRead($this->uid);
    } else {
      return FALSE;
    }
  }

  public function getMyExam() {
    $userInfo = $this->modelUser->find($this->uid);
    $map = [
      'uid'    => $this->uid,
      'status' => 0,
    ];
    $paper = $this->modelPaper->where($map)->field('status,room_id,id')->find();
    if (!$paper) {
      return FALSE;
    } else {
      return ['paper' => $paper,
              'uid'   => $this->uid];
    }
  }

  private function checkExam() {
    //考试期内直接进入考试，不允许访问其他内容
    $myExam = self::getMyExam();
    if ($myExam) {
      $module = strtolower(request()->module());
      $controller = strtolower(request()->controller());
      $action = strtolower(request()->action());
      $rule = [
        'portal' => ['room'   => '*',
                     'notice' => ['read']],
      ];
      $accept = FALSE;

      if (isset($rule[ $module ][ $controller ])) {
        if ($rule[ $module ][ $controller ] === '*' || in_array($action, $rule[ $module ][ $controller ])) {
          $accept = TRUE;
        }
      }
      if (!$accept) {
        $url = url('portal/room/view', ['id' => $myExam['paper']['room_id']]);
        $this->redirect($url);
      } else {
        return;
      }
    }
    Cache::clear();
    $info = Cache::get('examInfo');
    if (!$info) {
      //查找已经开始的班级
      $info = $this->modelRoom->startedClass();
      if ($info) {
        Cache::set('examInfo', $info, new \DateTime($info['end_time']));
      }

      return;
    }
    //计算结束时间
    $minute = 0;
    $nowTimestamp = time();
    $endTimestamp = strtotime($info['end_time']);
    $overplusTime = $endTimestamp - $nowTimestamp;
    if ($overplusTime > 0) {
      $minute = floor($overplusTime / 60);
    }

    if ($minute == 0)
      $minute = 1;
    $timeStr = date('H:i', $endTimestamp);
    if ($info['class_id'] == 0) {
      $msg = '当前正在进行实验室安全考试的补考';
    } else {
      $msg = '当前' . $info['title'] . '正在进行实验室安全考试';
    }
    $msg .= "，系统暂停服务，大约{$minute}分钟，预计{$timeStr}恢复服务。<br/><br/>欢迎你再次来学习！";
    if (\request()->isMobile()) {
      $this->result('', -2, $msg);
    }
    $this->error($msg, url('base/login/index'), '', $overplusTime);
  }

  private function checkLogin() {
    $module = strtolower(request()->module());
    $controller = strtolower(request()->controller());
    $action = strtolower(request()->action());
    //允许未登录访问访问的列表
    $noLoginRule = [
      'base'   => ['login' => ['index',
                               'login'],],
      'portal' => ['login' => ['index',
                               'login'],],
    ];
    //未登录的跳转登录
    if (!Session::has('user_id')) {
      $accept = FALSE;
      if (isset($noLoginRule[ $module ])) {
        if ($noLoginRule[ $module ] === '*') {
          $accept = TRUE;
        } else {
          if (isset($noLoginRule[ $module ][ $controller ])) {
            if ($noLoginRule[ $module ][ $controller ] === '*' || in_array($action, $noLoginRule[ $module ][ $controller ])) {
              $accept = TRUE;
            }
          }
        }
      }
      if (!$accept) {
        if (request()->isAjax()) {
          $this->result([], -1, '权限不够，无法访问');
        }
        $this->error('您没有访问该栏目的权限', 'base/login/index');
      }
    } else {
      $this->uid = session('user_id');
    }

    return TRUE;
  }

  private function checkAccess() {
    $module = strtolower(request()->module());
    $controller = strtolower(request()->controller());
    $action = strtolower(request()->action());
    //允许未登录访问访问的列表
    $noLoginRule = [
      ['base' => ['login' => '*',],],
    ];
    //未登录的跳转登录
    if (!session('?user_id')) {
      $accept = FALSE;
      if ($noLoginRule[ $module ] == '*') {
        $accept = TRUE;
      } elseif ($noLoginRule[ $module ][ $controller ] === '*') {
        $accept = TRUE;
      } elseif ($noLoginRule[ $module ][ $controller ][ $action ] === '*') {
        $accept = TRUE;
      } elseif (in_array($action, $noLoginRule[ $module ][ $controller ][ $action ])) {
        $accept = TRUE;
      }
      if (!$accept) $this->error('权限不够，无法访问', 'base/login/index');
    } else {
      $this->uid = session('user_id');
    }

    return TRUE;
  }

}
